import "@wangeditor/editor/dist/css/style.css";
import { useCallback, useEffect, useState } from "react";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";

interface Props {
  html: string;
  setHtml: (html: string) => void;
  onChangeEffect: (text: string) => void;
  setTextLength: (length: number) => void;
}

const MyEditor = (props: Props) => {
  const [editor, setEditor] = useState<IDomEditor | null>(null);
  const toolbarConfig: Partial<IToolbarConfig> = {};
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: "请输入内容...",
  };

  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  const onChage = useCallback(
    (editor: IDomEditor) => {
      props.setHtml(editor.getHtml());
      props.onChangeEffect?.(editor.getHtml());
      props.setTextLength(editor.getText().length);
    },
    [editor, props.onChangeEffect],
  );

  return (
    <>
      <div style={{ border: "1px solid #ccc", zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{ borderBottom: "1px solid #ccc" }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={props.html}
          onCreated={setEditor}
          onChange={onChage}
          mode="default"
          style={{ height: "500px", overflowY: "hidden" }}
        />
      </div>
    </>
  );
};

export default MyEditor;
